package com.gxa.controller;

import com.gxa.common.JsonResult;
import com.gxa.common.PageRecv;
import com.gxa.common.R;

import com.gxa.pojo.Repository;
import com.gxa.service.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@Controller
@RequestMapping("/repository")
public class RepositoryController {
    @Autowired
    private RepositoryService repositoryService;
    //查询
    @RequestMapping(value = "/queryRep",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult queryEmpList(Integer currentPage,Integer pageSize){
        return repositoryService.queryRep(currentPage,pageSize);
    }

//    删除
    @RequestMapping(value = "/deleteRep",method = RequestMethod.POST)
    @ResponseBody
    public R deleteRepository(Integer id){
        return repositoryService.delRep(id);
    }

    //搜索
    @RequestMapping(value = "/selectRepList",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult selectRepList(@RequestBody PageRecv<Repository> pageRecv){
        JsonResult<Repository>repositoryJsonResult= repositoryService.searchRep(pageRecv);
        return repositoryJsonResult;
    }

//    修改
@RequestMapping(value = "/updateRep",method = RequestMethod.POST)
@ResponseBody
    public R updateRep(@RequestBody Repository repository){
        return repositoryService.updateRep(repository);
}

//    添加及文件上传
    @RequestMapping(value = "/addRep",method = RequestMethod.POST)
    @ResponseBody
    public R addRepository( Repository repository, HttpServletRequest request){
        R r=new R();
        if(repository.getAppendix().isEmpty()){
            r.setCode(500);
            r.setMsg("没有选中文件");
        }else{
            String uploadPath = request.getServletContext().getRealPath("") + File.separator + "upload" + File.separator;
            File file = new File(uploadPath);
            if(!file.exists()){
                file.mkdirs();
            }
            MultipartFile multipartFile = repository.getAppendix();
            String fileName = multipartFile.getOriginalFilename();
            File newFile = new File(uploadPath + fileName);
            System.out.println("newFile=" + newFile);
            try {
                //上传
                FileCopyUtils.copy(multipartFile.getBytes(),newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("文件名："+fileName);
            repository.setAppendix_name(fileName);
        }

        return repositoryService.addRep(repository);
    }


}
